package com.wwk.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.wwk.pojo.Permission;
import com.wwk.pojo.Role;
import com.wwk.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Classname SpringSecurityUserService
 * @Description TODO
 * @Date 2020/11/12 9:21
 * @Created by wwk
 * @Author wwk
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        final User userByname = userService.findUserByname(s);
        System.out.println("adadadaddaadasdadsadsadsa"+userByname);
        if(userByname==null){
            System.out.println("查询用户失败");
            return null;
        }

        List<GrantedAuthority> list=new ArrayList<>();
        //动态为当前用户授权
        final Set<Role> roles = userByname.getRoles();
        if(roles!=null&& roles.size()>0){
            for (Role role:roles) {
                //遍历角色,动态授予角色，并获得角色权限
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                final Set<Permission> permissions = role.getPermissions();
                for (Permission p :permissions) {
                    //遍历权限集合，为用户授权
                    list.add(new SimpleGrantedAuthority(p.getKeyword()));
                }
            }
        }
        UserDetails userDetails=
                new org.springframework.security.core.userdetails.User(s,userByname.getPassword(),list);
        return userDetails;
    }
}
